package com.rongc.client.freight.business.waybill.view.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.rongc.client.core.exception.RegexException;
import com.rongc.client.core.network.code.HandleCode;
import com.rongc.client.core.network.http.RequestManager;
import com.rongc.client.core.utils.ActivityUtils;
import com.rongc.client.core.utils.FileUtil;
import com.rongc.client.core.utils.ImageUtils;
import com.rongc.client.core.utils.LogUtils;
import com.rongc.client.core.utils.RegexUtil;
import com.rongc.client.freight.R;
import com.rongc.client.freight.base.BaseActivity;
import com.rongc.client.freight.base.request.result.NullResult;
import com.rongc.client.freight.base.view.widget.BGASortableNinePhotoLayoutTemp;
import com.rongc.client.freight.business.waybill.request.api.WaybillHuidanApi;
import com.rongc.client.freight.utils.UtilMethod;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by ccqx on 2017/8/19.
 */

public class HuidanActivity extends BaseActivity implements
        BGASortableNinePhotoLayoutTemp.Delegate,
        EasyPermissions.PermissionCallbacks{
    @Bind(R.id.et_content)
    EditText mEtContent;
    @Bind(R.id.activity_discover_invest_publish_nine_photo)
    BGASortableNinePhotoLayoutTemp ninePhotoLayout;
    String path;
    String waybillid ;
    private static final int REQUEST_CODE_PERMISSION_PHOTO_PICKER = 1;

    public static final int REQUEST_CODE_CHOOSE_PHOTO = 1;
    public static final int REQUEST_CODE_PHOTO_PREVIEW = 12;
    public static final int MAX_PHOTO_COUNT = 1;

    Response.Listener<NullResult> respOrderListener = new Response.Listener<NullResult>() {

        @Override
        public void onResponse(NullResult response) {
            if (HandleCode.requestSuccess()) {
                FileUtil.clearDir(FileUtil.getTempFile());
                finish();
            } else {
                UtilMethod.dismissProgressDialog(HuidanActivity.this);
            }
        }
    };

    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            LogUtils.i("error.getMessage(): " + error.getMessage());
            UtilMethod.dismissProgressDialog(HuidanActivity.this);
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_submit, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_submit:
                try{
                    path = "";
                    if(ninePhotoLayout.getData().size()>0)
                        path = ninePhotoLayout.getData().get(0);

                    prepare();
                    doUpload();
                }catch (RegexException e){
                    ActivityUtils.toast(e.getMessage());
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_PHOTO) {
            ninePhotoLayout.setData(BGAPhotoPickerActivity.getSelectedImages(data));
        } else if (requestCode == REQUEST_CODE_PHOTO_PREVIEW) {
            ninePhotoLayout.setData(BGAPhotoPickerPreviewActivity.getSelectedImages(data));
        }
    }

    private void doUpload(){
        ActivityUtils.toast("图片处理中...");
        mEtContent.postDelayed(new Runnable() {
            @Override
            public void run() {
                File file = ImageUtils.makePaths2ImgFil(path);
                UtilMethod.showProgressDialog(HuidanActivity.this, "正在上传...");
                WaybillHuidanApi p = new WaybillHuidanApi(respOrderListener, errorListener, "img", file,
                        new WaybillHuidanApi.WaybillHuidanParams(waybillid,mEtContent.getText().toString()));
                RequestManager.getInstance().call(p);
            }
        },100);
    }

    void prepare() throws RegexException {
        if(!RegexUtil.checkNotNull(path)){
            throw new RegexException("请选择上传图片");
        }
    }

    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_PHOTO_PICKER)
    private void choicePhotoWrapper() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "FreDownload");

            startActivityForResult(BGAPhotoPickerActivity.newIntent(this, takePhotoDir, MAX_PHOTO_COUNT, null), REQUEST_CODE_CHOOSE_PHOTO);
        } else {
            EasyPermissions.requestPermissions(this, "图片选择需要以下权限:\n\n1.访问设备上的照片", REQUEST_CODE_PERMISSION_PHOTO_PICKER, perms);
        }
    }

    @Override
    public void initParams() {
        waybillid = getIntent().getStringExtra("waybillid");
    }

    @Override
    public void initView() {
        initToolbar("上传回单");
        ninePhotoLayout.init(this);
        ninePhotoLayout.setDelegate(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_huidan;
    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayoutTemp sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        choicePhotoWrapper();
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayoutTemp sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        ninePhotoLayout.removeItem(position);
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayoutTemp sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        startActivityForResult(BGAPhotoPickerPreviewActivity.newIntent(this, MAX_PHOTO_COUNT, models, models, position, false), REQUEST_CODE_PHOTO_PREVIEW);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == REQUEST_CODE_PERMISSION_PHOTO_PICKER) {
            Toast.makeText(this, "您拒绝了「图片选择」所需要的相关权限!", Toast.LENGTH_SHORT).show();
        }
    }
}
